package com.whh.controller;

import javax.servlet.http.HttpServletRequest;

import com.whh.config.exception.APIException;
import com.whh.config.vo.ResultCode;
import com.whh.config.vo.ResultVO;
import com.whh.entity.TokenEntity;
import com.whh.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.whh.entity.ResultEntity;
import com.whh.entity.SysUserEntity;
import com.whh.service.LoginService;

@RestController
@RequestMapping(value="/login")
public class LoginController extends BaseController<SysUserEntity> {
	
	@Autowired
	private LoginService service;

	@Autowired
	private TokenService tokenService;
	
	@RequestMapping(value="/search",method=RequestMethod.POST)
	@ResponseBody
	public ResultVO<String> commit(SysUserEntity entity, HttpServletRequest request) {
		if (StringUtils.isEmpty(entity.getLoginName()) || StringUtils.isEmpty(entity.getPassword())) {
			throw new APIException(ResultCode.VALIDATE_FAILED,"用户名或密码为空");
		}
		SysUserEntity user = service.commit(entity);
		if (user == null) {
			throw new APIException(ResultCode.NOT_FOUND, "用户不存在");
		}
		TokenEntity tokenEntity = tokenService.createToken(String.valueOf(user.getId()));
		return new ResultVO<String>(tokenEntity.getToken());
	}
	

}
